package com.lagou.edu.course.remote;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lagou.edu.common.util.ConverUtil;
import com.lagou.edu.common.util.ConvertUtils;
import com.lagou.edu.course.api.dto.CourseDTO;
import com.lagou.edu.course.api.dto.LessonDTO;
import com.lagou.edu.course.api.dto.TeacherDTO;
import com.lagou.edu.course.api.enums.CourseLessonStatus;
import com.lagou.edu.course.api.enums.CourseStatus;
import com.lagou.edu.course.api.param.CourseQueryParam;
import com.lagou.edu.course.entity.Course;
import com.lagou.edu.course.entity.Lesson;
import com.lagou.edu.course.entity.Teacher;
import com.lagou.edu.course.service.ICourseService;
import com.lagou.edu.course.service.ILessonService;
import com.lagou.edu.course.service.ITeacherService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 课程Service
 *
 * @author lm
 * @since 2021/10/25 11:28
 */
@Service
@Slf4j
public class CourseService {
    @Autowired
    ICourseService iCourseService;

    @Autowired
    ITeacherService iTeacherService;

    @Autowired
    ILessonService iLessonService;

    public List<CourseDTO> getAllCourse(Integer userId) {
        log.info("getAllCourses - userId:{}", userId);
        // 获取有效的课程
        List<Course> courses = getInvalidCourses();
        if (CollectionUtils.isEmpty(courses)) {
            log.info("[选课列表] 获取选课列表信息为空");
            return Collections.emptyList();
        }
        // TODO 获取用户课程订单
        // Map<Integer, UserCourseOrderDTO> orderMap = getUserCourseOrderMapForCourseList(userId);
        List<CourseDTO> courseDTOList = new ArrayList<>();
        for (Course course : courses) {
            CourseDTO courseDTO = new CourseDTO();
            BeanUtils.copyProperties(course, courseDTO);
            courseDTOList.add(courseDTO);
        }
        //未购上新课程
        List<CourseDTO> newCourseList = new LinkedList<>();
        //未购课程
        List<CourseDTO> notPayCourseList = new LinkedList<>();
        //已购课程
        List<CourseDTO> payedCourseList = new LinkedList<>();
        for (CourseDTO courseDTO : courseDTOList) {
            Integer courseId = courseDTO.getId();
            // 设置购买标识
            //setBuyFlag(orderMap, courseDTO, courseId);
            // 设置老师的信息
            setTeacher(courseDTO);
            // 设置topN课时
            setTopNCourseLesson(courseDTO);
            //保存上新且未购买的课程
            if (!courseDTO.getIsBuy() && StringUtils.isNotBlank(courseDTO.getDiscountsTag())) {
                //hasActivityCourse(courseDTO);
                newCourseList.add(courseDTO);
                continue;
            }
            //未购买课程
            if (!courseDTO.getIsBuy()) {
                //hasActivityCourse(courseDTO);
                notPayCourseList.add(courseDTO);
                continue;
            }
            //已购买的课程列表
            payedCourseList.add(courseDTO);

        }

        //遍历组装courseList信息
        List<CourseDTO> courseList = new LinkedList<>();
        courseList.addAll(newCourseList);
        courseList.addAll(notPayCourseList);
        courseList.addAll(payedCourseList);
        return courseList;
    }

    /**
     * 获取有效课程
     *
     * @return 有效课程
     */
    private List<Course> getInvalidCourses() {
        return iCourseService.lambdaQuery().eq(Course::getStatus, CourseStatus.PUTAWAY.getCode())
                .eq(Course::getIsDel, Boolean.FALSE)
                .orderByDesc(Course::getSortNum)
                .list();
    }

    private void setTeacher(CourseDTO courseDTO) {
        List<Teacher> teachers = iTeacherService.lambdaQuery().eq(Teacher::getCourseId, courseDTO.getId())
                .eq(Teacher::getIsDel, Boolean.FALSE)
                .list();
        if (CollectionUtils.isEmpty(teachers)) {
            return;
        }
        TeacherDTO teacherDTO = new TeacherDTO();
        BeanUtils.copyProperties(teachers.get(0), teacherDTO);
        courseDTO.setTeacherDTO(teacherDTO);
    }

    /**
     * 获取topN课程
     *
     * @param courseDTO
     */
    private void setTopNCourseLesson(CourseDTO courseDTO) {
        List<Lesson> lessons = iLessonService.lambdaQuery().ne(Lesson::getStatus, CourseLessonStatus.HIDE.getCode())
                .eq(Lesson::getCourseId, courseDTO.getId())
                .eq(Lesson::getIsDel, Boolean.FALSE)
                .orderByAsc(Lesson::getSectionId, Lesson::getOrderNum)
                .last("limit 0, 2")
                .list();
        if (CollectionUtils.isEmpty(lessons)) {
            return;
        }
        List<LessonDTO> lessonDTOS = ConverUtil.convertList(lessons, LessonDTO.class);
        courseDTO.setTopNCourseLesson(lessonDTOS);
    }

    public List<CourseDTO> getPurchasedCourse(Integer userId) {
        return null;
//        if (userId == null) {
//            return Collections.emptyList();
//        }
//        // 1、 获取订单信息
//        //ResponseDTO<List<UserCourseOrderDTO>> ordersResult = userCourseOrderRemoteService.getUserCourseOrderByUserId(userId);
//        //List<UserCourseOrderDTO> userCourseOrderDTOS = ordersResult.getContent();
//        if(CollectionUtils.isEmpty(userCourseOrderDTOS)){
//            log.info("[获取已购课程]  用户课程订单不存在，userId:{}",userId);
//            return Collections.EMPTY_LIST;
//        }
//        //通过订单获取购买的课程Ids
//        List<Integer> courseIds = userCourseOrderDTOS.stream().map(UserCourseOrderDTO::getCourseId).collect(Collectors.toList());
//        List<Course> coursesList = getCourseByIds(courseIds);
//        if (CollectionUtils.isEmpty(coursesList)) {
//            return Collections.emptyList();
//        }
//        //获取已播放和未播放的课程
//        List<CourseDTO> finalResultList = new ArrayList<>();
//        for (Course course : coursesList) {
//            Integer courseId = course.getId();
//            CourseDTO courseDTO = new CourseDTO();
//            CoursePlayHistoryDTO recordLearn = coursePlayHistoryService.getRecordLearn(courseId, userId);
//            if(recordLearn != null){
//                Integer lessonId = recordLearn.getLessonId();
//                Lesson lesson = lessonService.getById(lessonId);
//                if(lesson != null){
//                    courseDTO.setLastLearnLessonName(lesson.getTheme());
//                }
//            }
//            BeanUtils.copyProperties(course,courseDTO);
//            // 设置课程更新数量
//            setLessonUpdateCount(courseId, courseDTO);
//            // 设置课程的最近播放时间
//            setCourseLastPlayTimeAndLessonName(userId,course.getId(),courseDTO);
//
//            //根据支付时间和播放时间，重设待排序比较时间
//            resetCompareDate(courseDTO,userCourseOrderDTOS);
//            finalResultList.add(courseDTO);
//        }
//
//        //按播放时间排序
//        sortByCompareTime(finalResultList);
//        return finalResultList;
    }


    public CourseDTO getCourseById(Integer courseId, Integer userId) {
        Course course = iCourseService.getById(courseId);
        if (course != null) {
            CourseDTO courseDTO = ConvertUtils.convert(course, CourseDTO.class);

            Teacher teacher = iTeacherService.lambdaQuery().eq(Teacher::getCourseId, courseId).one();
            courseDTO.setTeacherDTO(ConverUtil.convert(teacher, TeacherDTO.class));

            return courseDTO;
        } else {
            return null;
        }
    }

    public boolean saveOrUpdateCourse(CourseDTO courseDTO) {
        Course course = new Course();
        BeanUtil.copyProperties(courseDTO, course);
        course.setUpdateTime(LocalDateTime.now());
        course.setCreateTime(LocalDateTime.now());

        log.info("保存的课程信息：{}", JSONUtil.toJsonStr(course));
        boolean res = iCourseService.saveOrUpdate(course);
        TeacherDTO teacherDTO = courseDTO.getTeacherDTO();
        if (teacherDTO == null) {
            return Boolean.TRUE;
        }
        Teacher teacher = new Teacher();
        BeanUtil.copyProperties(teacherDTO, teacher);
        teacher.setCourseId(course.getId());
        teacher.setUpdateTime(LocalDateTime.now());
        teacher.setCreateTime(LocalDateTime.now());
        log.info("保存老师的信息为 teacher:{}", JSONUtil.toJsonStr(teacher));
        iTeacherService.saveOrUpdate(teacher);
        return iCourseService.save(course);
    }

    public boolean changeState(Integer courseId, Integer status) {
        Course course = iCourseService.getById(courseId);
        if (course == null) {
            return false;
        }
        course.setStatus(status);
        return iCourseService.updateById(course);
    }

    public Page<CourseDTO> getQueryCourses(CourseQueryParam courseQueryParam) {
        String courseName = courseQueryParam.getCourseName();
        Integer status = courseQueryParam.getStatus();
        Integer currentPage = courseQueryParam.getCurrentPage();
        Integer pageSize = courseQueryParam.getPageSize();

        Page<Course> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(courseName)) {
            queryWrapper.like("course_name", courseName);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        int count = iCourseService.count(queryWrapper);
        queryWrapper.orderByDesc("id");
        IPage<Course> selectPage = iCourseService.getBaseMapper().selectPage(page, queryWrapper);

        List<CourseDTO> courseDTOS = new ArrayList<>();

        for (Course course : selectPage.getRecords()) {
            CourseDTO courseDTO = new CourseDTO();
            BeanUtil.copyProperties(course, courseDTO);
            courseDTOS.add(courseDTO);
        }

        Page<CourseDTO> result = new Page<>();
        //分页查询结果对象属性的拷贝
        BeanUtil.copyProperties(selectPage, result);
        //设置分页结果对象record属性
        result.setRecords(courseDTOS);
        result.setTotal(count);
        return result;
    }
}
